package core;

import java.awt.AWTException;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MainButton extends JFrame implements ActionListener, MouseMotionListener, MouseListener {
	
	private static final long serialVersionUID = 1L;
	long lastRightClick = System.currentTimeMillis();
	Robot bot;
	StartupWindow startupWindow;
	
	public MainButton() {
		startupWindow = new StartupWindow();
		
		try {
			bot = new Robot();
		} catch (AWTException e) {}
		
		JButton magicButton = new JButton("Undo");
		magicButton.addActionListener(this);
		magicButton.addMouseListener(this);
		magicButton.addMouseMotionListener(this);
		add(magicButton);
		
		setUndecorated(true);
		setFocusableWindowState(false);
		setAlwaysOnTop(true);
		setShape(new Ellipse2D.Double(10, 10, 50, 50));
		setBounds(startupWindow.getX() + startupWindow.getWidth()/2 - 35, startupWindow.getY(), 70, 70);
		setVisible(true);
	}
	
	private void closeStartupWindow() {
		if (startupWindow != null) {
			startupWindow.dispose();
			startupWindow = null;
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent evt) {
		closeStartupWindow();
		bot.keyPress(KeyEvent.VK_CONTROL);
		bot.keyPress(KeyEvent.VK_Z);
		bot.keyRelease(KeyEvent.VK_Z);
		bot.keyRelease(KeyEvent.VK_CONTROL);
	}
	
	@Override
	public void mouseDragged(MouseEvent evt) {
		closeStartupWindow();
		if (SwingUtilities.isRightMouseButton(evt)) {
			Point target = evt.getLocationOnScreen();
			target.translate(-35, -35);
			setLocation(target);
		}
	}
	
	@Override
	public void mouseClicked(MouseEvent evt) {
		closeStartupWindow();
		if (SwingUtilities.isRightMouseButton(evt)) {
			long currentRightClick = System.currentTimeMillis();
			if (currentRightClick - lastRightClick < 500) {
				System.exit(0);
			}
			lastRightClick = currentRightClick;
		}
	}
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new MainButton();
			}
		});
	}
	
	//Unused Methods
	@Override
	public void mouseMoved(MouseEvent evt) {}

	@Override
	public void mouseEntered(MouseEvent evt) {}

	@Override
	public void mouseExited(MouseEvent evt) {}

	@Override
	public void mousePressed(MouseEvent evt) {}

	@Override
	public void mouseReleased(MouseEvent evt) {}
	
}
